<template>
  <div class="app-container">

    <div class="div-title" style="border-radius: 4px">
      <span>门店班次设置</span>
    </div>

    <div class="divTable">
      <el-table border v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
        <el-table-column label="门店名称" align="center" prop="storeName" width="300px"/>
        <el-table-column label="班次代码" align="center" prop="workType" />
        <el-table-column label="班次" align="center" prop="workName" />
        <el-table-column label="上班时间" align="center" prop="timeStr" width="260px" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.startTime }}-
              {{ scope.row.endTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="限制人数" align="center" prop="limitNumber" />

        <el-table-column label="间隔时间" align="center" prop="intervalMinute" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>


    </div>

    <div class="div-title" style="border-radius: 4px">
      <span>门店班次设置</span>
    </div>

    <div>

      <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
        label-width="80px">

        <el-row>


          <el-form-item label="经营状态" prop="occupationStatus">
            <el-radio v-model="occupationStatus" label="1" @input="changeOccupationStatus">经营</el-radio>
            <el-radio v-model="occupationStatus" label="0" @input="changeOccupationStatus">休息</el-radio>
          </el-form-item>
        </el-row>
        <!-- <el-row>
          <el-form-item label="日期设置" prop="date">
            <el-radio v-model="dateTimeStatus" @input="changeTimeStatus" label="0">不设置休息日期</el-radio>
            <el-radio v-model="dateTimeStatus" @input="changeTimeStatus" label="1">设置休息日期</el-radio>
          </el-form-item>
        </el-row> -->
        <!-- <el-row v-if="(dateTimeStatus == 1)">
          <el-form-item label=" ">
            休息时间:
            <el-date-picker v-model="queryParams.applyAuthTimeArray" type="daterange" align="right" style="width: 232px"
              value-format="yyyy-MM-dd" unlink-panels range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>

            <el-button v-if="this.userInfo.storeId" style="margin-left: 20px;" size="mini" type="text"
              @click="addWorkDate()">新增一条休息日期</el-button>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label=" ">
            <el-table border :data="timeList">
              <el-table-column label="休息时间" align="center" prop="workDate" width="160px" />

              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit"
                    @click="delWorkById(scope.row.planId)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

          </el-form-item>
          <div style="margin-right:65%">
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="listByStore" />
          </div>
        </el-row> -->


      </el-form>

    </div>


    <!-- 添加或修改班次/系列对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body @keyup.enter.native="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">

        <el-form-item label="班次名称" prop="workName">
          <el-col :span="9">
            <el-input v-model="form.workName" placeholder="请输入班次名称" maxlength="50"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="上班时间" prop="startTime">
          <el-col :span="12">

            <el-time-select v-model="form.startTime" style="width: 215px" :picker-options="{
  start: '00:00',
  step: '00:15',
  end: form.endTime
}">
            </el-time-select>

          </el-col>
        </el-form-item>

        <el-form-item label="下班时间" prop="endTime">
          <el-col :span="12">

            <el-time-select v-model="form.endTime" style="width: 215px" :picker-options="{
  start: form.startTime,
  step: '00:15',
  end: '23:59'
}">
            </el-time-select>

          </el-col>
        </el-form-item>

        <el-form-item label="间隔时间" prop="intervalMinute">
          <el-col :span="9">
            <el-input v-model="form.intervalMinute" placeholder="请输入间隔时间" maxlength="4" show-word-limit
              @input="form.intervalMinute = onInput(form.intervalMinute, 0)" />
          </el-col>
        </el-form-item>

        <el-form-item label="限制人数" prop="limitNumber">
          <el-col :span="9">
            <el-input-number style="width:100%;" :controls="false" :precision="0" :step="0" :min="0" :max="99"
              v-model="form.limitNumber"></el-input-number>
          </el-col>
        </el-form-item>


        <!-- <span class="to-send-time-label">间隔时间</span>
                  <el-time-select
                    v-model="ruleForm.sendTime"
                    style="width: 215px"
                    :picker-options="{
                      start: '00:00',
                      step: '00:15',
                      end: '23:59'
                    }"
                  >
                  </el-time-select> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  updateStatus, getStore
} from "@/api/platform/store";

import {
  listWork,
  getWork,
  delWork,
  addWork,
  updateWork,
  updateWorkStatus,
  listByStoreId, toSetMonthPlan, delWorkP
} from "@/api/service/workSet";
import { onInput } from "@/utils/util";
import { mapGetters } from 'vuex'
import imageArraySize from "@/components/ImageUpload/imageArraySize";
export default {
  name: "Work",
  components: {
    imageArraySize,
  },
  data() {
    return {
      occupationStatus: "",
      dateTimeStatus: "",
      getTime: [],
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中数组的名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班次/系列表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用于类别关联的分类显示
      dialogVisible: false,
      //常用状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,

        dataStatus: null,
      },

      // 表单参数
      form: {
        dialogImageUrl: "",
        dataPriority: "",
        startTime: '00:00'
      },
      // 表单校验
      rules: {
        workName: [{
          required: true,
          message: "班次名称不能为空",
          trigger: "blur"
        }],
        startTime: [{
          required: true,
          message: "上班时间不能为空",
          trigger: "blur"
        }],
        endTime: [{
          required: true,
          message: "下班时间不能为空",
          trigger: "blur"
        }],
        intervalMinute: [{
          required: true,
          message: "间隔时间不能为空",
          trigger: "blur"
        }],



      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      queryForm: {
        applyAuthTimeArray: [],
      },
      timeList: [],
    };
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  created() {
    this.getList();
    this.listByStore();
    // this.getDicts("sys_data_status").then((response) => {
    //   this.statusOptions = response.data;
    // });
    if (this.userInfo.storeId) {
      getStore(this.userInfo.storeId).then(response => {
        if (response.data) {
          this.occupationStatus = response.data.occupationStatus
          this.dateTimeStatus = response.data.timeStatus

        }
      })
    }

  },
  methods: {
    changeOccupationStatus() {
      const $this = this;
      let da = this.occupationStatus;
      let text = this.occupationStatus === "0" ? "休息" : "营业";
      this.$confirm(
        '确定要把营业状态设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          console.log(this.userInfo)
          let data = {
            storeUid: this.userInfo.storeId,
            occupationStatus: this.occupationStatus
          }
          return updateStatus(data);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.listByStore();
        }).catch(function () {
          $this.occupationStatus = da === "0" ? "1" : "0";
        });

    },
    changeTimeStatus() {
      if (this.dateTimeStatus == '0') {
        this.timeList = [];
      }
      let data = {
        storeUid: this.userInfo.storeId,
        timeStatus: this.dateTimeStatus
      }
      updateStatus(data).then(() => {
        this.msgSuccess("操作成功");
        this.listByStore();
      })
    },
    dataPriorityInput(value) {
      let js = value + "";
      return js.replace(/^(0+)|[^\d]+/g, "");
    },

    onInput,
    /** 查询班次/系列列表 */
    getList() {
      this.loading = true;
      listWork(this.queryParams).then((response) => {
        this.brandList = response.rows;
        this.loading = false;
      });
    },
    delWorkById(id) {
      let arr = [id]
      delWorkP(arr).then(response => {
        this.msgSuccess("操作成功");
        this.listByStore();
      });
    },
    listByStore() {
      listByStoreId(this.queryParams).then((response) => {
        this.timeList = response.rows;
        this.total = response.total;
      });
    },
    handleRemove(file, fileList) { },
    handlePictureCardPreviewLogo(file) {
      this.logoUr = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreviewImg(file) {
      this.deviceImage = file.url;
      this.dialogVisible = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },



    // 关联的取消按钮
    cancelWork() {
      this.openWork = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 班次菜单 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.workId);
      this.names = selection.map((item) => item.deviceName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.dataStatus) {
            this.multiple = true;
            break;
          }
        }
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班次";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const workId = row.workId || this.ids;
      getWork(workId).then((response) => {
        this.form = response.data;
        // console.log(this.form);
        this.open = true;
        this.title = "修改班次";
      });
    },
    addWorkDate() {
      if (this.queryParams.applyAuthTimeArray && this.queryParams.applyAuthTimeArray.length > 0) {
        let data = {
          storeId: this.userInfo.storeId,
          startDate: this.queryParams.applyAuthTimeArray[0],
          endDate: this.queryParams.applyAuthTimeArray[1],
          workStatus: 0,
          workType: "rest"
        }
        toSetMonthPlan(data).then((response) => {
          this.msgSuccess("新增成功");
          this.listByStore();
        });
      } else {
        this.$message.error('请选择日期');
      }

    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.workId != null) {
            updateWork(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWork(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },


  },
};
</script>
<style lang="scss" scoped>
.treeOne {
  display: inline-block;
  margin-right: 200px;
}

.treeTwo {
  display: inline-block;
}

.image-rows {
  width: 80px;
  height: auto;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.block {
  padding: 30px 0;
  text-align: center;
  display: inline-block;
  vertical-align: top;
}

.app-container {
  background-color: #F7F8FA;
  padding: 20px;
}

.font-normal1 {
  font-size: 12px;
  color: #84868a;
  margin-top: -5px;
}

.font-normal {
  font-size: 12px;
  color: #84868a;
  margin-top: -6px;
}

.div-title {
  background-color: rgb(242, 246, 252);
  margin: 15px;
  padding: 10px 10px 10px 10px;
  font-weight: 500;
}

.dw {
  z-index: 2000;
  border: 1px;
  position: fixed;
  bottom: 0px;
  background-color: #f7f8fa;
  width: 100%;
  height: 55px;
}
</style>
